#include "multiscreenwidget.h"
#include <QApplication>
#include <QScreen>
#include <QPainter>
#include <QKeyEvent>
#include <QDebug>

MultiScreenWidget::MultiScreenWidget(QWidget *parent)
    : QWidget(parent)
    , protocol(nullptr)
    , fullScreenMode(false)
    , scaleX(1.0)
    , scaleY(1.0)
{
    setAttribute(Qt::WA_OpaquePaintEvent, true);
    setAttribute(Qt::WA_NoSystemBackground, true);
    setMouseTracking(true);
    
    // 初始化屏幕信息
    for (QScreen *screen : QApplication::screens()) {
        screenGeometries.append(screen->geometry());
        screenAvailableGeometries.append(screen->availableGeometry());
    }
    
    // 计算虚拟几何
    if (!screenGeometries.isEmpty()) {
        virtualGeometry = screenGeometries.first();
        for (const QRect &rect : screenGeometries) {
            virtualGeometry = virtualGeometry.united(rect);
        }
    }
}

MultiScreenWidget::~MultiScreenWidget()
{
}

void MultiScreenWidget::setProtocol(Protocol *protocol)
{
    this->protocol = protocol;
}

void MultiScreenWidget::setScreenLayout(const QList<QRect> &screenGeometries)
{
    this->screenGeometries = screenGeometries;
    
    // 重新计算虚拟几何
    if (!screenGeometries.isEmpty()) {
        virtualGeometry = screenGeometries.first();
        for (const QRect &rect : screenGeometries) {
            virtualGeometry = virtualGeometry.united(rect);
        }
    }
    
    updateLayout();
    update();
}

void MultiScreenWidget::updateDesktop(const QImage &image)
{
    if (image.isNull())
        return;
        
    desktopImage = image;
    
    // 计算缩放比例
    if (!desktopImage.isNull() && !virtualGeometry.isEmpty()) {
        scaleX = (double)desktopImage.width() / virtualGeometry.width();
        scaleY = (double)desktopImage.height() / virtualGeometry.height();
    }
    
    update();
}

void MultiScreenWidget::setFullScreen(bool fullScreen)
{
    if (fullScreenMode != fullScreen) {
        fullScreenMode = fullScreen;
        
        if (fullScreen) {
            // 进入全屏模式，覆盖所有屏幕的可用区域
            ScreenManager screenManager;
            QRect layout = screenManager.getOptimalMultiScreenLayout();
            setGeometry(layout);
            showFullScreen();
        } else {
            showNormal();
        }
    }
}

bool MultiScreenWidget::isFullScreen() const
{
    return fullScreenMode;
}

void MultiScreenWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);
    
    if (desktopImage.isNull()) {
        // 绘制等待文本
        painter.setPen(Qt::white);
        painter.drawText(rect(), Qt::AlignCenter, tr("正在连接到远程桌面..."));
        return;
    }
    
    // 在每个屏幕区域绘制对应的桌面内容
    for (int i = 0; i < screenAvailableGeometries.size() && i < screenGeometries.size(); ++i) {
        const QRect &screenGeom = screenGeometries[i];
        const QRect &availableGeom = screenAvailableGeometries[i];
        
        // 计算在远程桌面中的对应区域
        QRect remoteScreenRect(
            screenGeom.x() * scaleX,
            screenGeom.y() * scaleY,
            screenGeom.width() * scaleX,
            screenGeom.height() * scaleY
        );
        
        // 从远程桌面图像中提取该区域
        QImage screenImage = desktopImage.copy(remoteScreenRect);
        
        // 缩放到本地屏幕可用区域
        QImage scaledImage = screenImage.scaled(availableGeom.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        
        // 绘制到对应位置
        painter.drawImage(availableGeom, scaledImage);
    }
}

void MultiScreenWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    update(); // 重绘窗口
}

void MultiScreenWidget::keyPressEvent(QKeyEvent *event)
{
    if (protocol) {
        protocol->sendKeyEvent(event->key(), true);
    }
    
    // 检查是否按下了退出全屏的组合键
    if (event->key() == Qt::Key_Escape) {
        if (fullScreenMode) {
            setFullScreen(false);
        } else {
            // 可以在这里添加退出应用的逻辑
        }
    }
    
    QWidget::keyPressEvent(event);
}

void MultiScreenWidget::mousePressEvent(QMouseEvent *event)
{
    if (protocol) {
        QPoint remotePos = mapToRemoteCoordinates(event->pos());
        protocol->sendMouseEvent(remotePos, event->button(), true);
    }
    
    QWidget::mousePressEvent(event);
}

void MultiScreenWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (protocol) {
        QPoint remotePos = mapToRemoteCoordinates(event->pos());
        protocol->sendMouseEvent(remotePos, event->button(), false);
    }
    
    QWidget::mouseReleaseEvent(event);
}

void MultiScreenWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (protocol) {
        QPoint remotePos = mapToRemoteCoordinates(event->pos());
        protocol->sendMouseEvent(remotePos, Qt::NoButton, false);
    }
    
    QWidget::mouseMoveEvent(event);
}

void MultiScreenWidget::setupScreens()
{
    // 设置屏幕相关参数
}

void MultiScreenWidget::updateLayout()
{
    // 更新布局信息
}

QRect MultiScreenWidget::mapToRemoteCoordinates(const QPoint &localPos) const
{
    // 将本地坐标映射到远程桌面坐标
    int remoteX = localPos.x() * scaleX;
    int remoteY = localPos.y() * scaleY;
    return QRect(remoteX, remoteY, 1, 1);
}